var app = window.lirlu = {};
app.esced = new Date();
app.pages = [];
app.wxDebug = false;
app.wxApiList = [
  'previewImage', 
  'chooseImage', 
  'uploadImage', 
  'onMenuShareTimeline', 
  'onMenuShareAppMessage', 
  'onMenuShareQQ',
  'onMenuShareQZone',
  'onMenuShareWeibo',
];
app.link = {
	'server' : 'http://tongxing.cdlinglu.cn/WeChat',
  'image'  : 'http://tongxing.cdlinglu.cn',
  'upload' : 'http://tongxing.cdlinglu.cn/Files/Upload',
  'share'  : 'http://tongxing.cdlinglu.cn/',
  'ally'   : 'http://tongxing.cdlinglu.cn/',
	'weixin' : 'http://tongxing.cdlinglu.cn/weixin'
}

// 为普通WEB作hack让plus部分代码不报错
// setTimeout(function () {
if (!window.plus) {
  $(document).ready(function () {
    var view = {
      'id'        : '',
      'isVisible' : function () { return true; },
      'hide'      : function () {},
      'show'      : function () {},
      'evalJS'    : function (code) {},
      'close'     : function () { app.open(app.popHis()); },
      'append'    : function (dom) { $('body').append(dom); },
      'parent'    : function () { return this; },
      'extras'    : $.extend({}, app.parseQueryString())
    }
    window.plus = {
      'nativeUI' : {
        'toast'        : app.toast,
        'showWaiting'  : function () {},
        'closeWaiting' : function () {},
        'alert'        : function (msg, callback) {
          app.toast(msg);
          return callback && callback.call();
        }
      },
      'webview' : {
        'currentWebview' : function () {
          return view;
        },
        'getWebviewById' : function () {
          return view;
        },
        'getLaunchWebview' : function () {
          return view;
        },
      },
      'screen' : {
        'lockOrientation' : function () {}
      },
      'share': {
        'getServices': function () {}
      }
    }; 

    if (mui.os.wechat) {
      var cart = window.cart = {};
      cart.add = function (data, cb) {
        data = data || {};
        
        data.token              = app.store('token');
        data.goods_id           = data.id;
        data.goods_num          = data.quantity;
        data.goods_attr_val_ids = (data.sku || []).join(',');
        
        plus.nativeUI.showWaiting('加入购物车...');
        app.log('请求参数：', data);
        $.ajax({
          'dataType' : 'json',
          'type'     : 'post',
          'url'      : app.url('App/Cart/Index/create'),
          'data'     : data,
        })
        .fail(function (res) {
          // 失败回调
          plus.nativeUI.closeWaiting();
          app.toast('加入购物车失败');
          app.log('加入购物车失败：', res);
        })
        .done(function (res) {
          // 成功回调
          plus.nativeUI.closeWaiting();
          app.log('加入购物车：', res);
          
          if (300 == res.code) { app.toast(res.msg); return; }
          if (200 != res.code) { app.toast('请求失败'); return; }
          if (res.msg) { app.toast(res.msg); } else { app.toast('加入购物车成功'); }
          
          cb && cb(res);
        })
        ;
      }
    }
  });
}

mui.back = function () {
  app.open(app.popHis());
}
mui.plusReady = function (cb) {
  $(document).ready(cb);
}
// }, 10);

/**
 * 微信初始化
 * @param  {Function} cb 回调函数
 * @return {Object}            
 */
app.wxInit = function (cb) {
  if (!wx) {
    app.log('请确保微信JSSDK文件已引入并且顺序正确');
    return;
  }
  $.ajax({
    'dataType' : 'json',
    'type'     : 'post',
    'url'      : app.url('/Index/Index/getJsSdk'),
    'data'     : { token: app.store('token'), data: { url: encodeURI(document.URL)}}
  })
  .fail(function (res) {
    app.log('获取微信配置信息失败：', res);
    if (cb && cb.error) return cb.error(res);
  })
  .done(function (res) {
    app.log('获取微信配置信息：', res);
    var config = {
      debug: app.wxDebug, 
      appId: res.data.appId, 
      timestamp: res.data.timestamp, 
      nonceStr: res.data.nonceStr,
      signature: res.data.signature,
      jsApiList: app.wxApiList
    };
    wx.config(config);
    wx.ready(cb.success);
    wx.error(cb.error);
  });
}

/**
 * 获取微信code
 * @param  {Object} appid   微信appid
 * @param  {Object} isRetry 是否重新获取
 */
app.getWxCode = function (appid, isRetry) {
  var code = app.getQueryString('code') || app.store('code');
  if (code && !isRetry) {
    app.log('获取code成功：', code);
    app.store('code', code);
    return code;
  }
  var queryString = {
    appid: appid,
    redirect_uri: document.URL,
    response_type: 'code',
    scope: 'snsapi_userinfo',
    state: 'STATE#wechat_redirect',
  };
  app.open('https://open.weixin.qq.com/connect/oauth2/authorize', queryString);
}

/**
 * 获取微信appid
 * @param  {Function} cb 回调函数
 */
app.getAppid = function (cb) {
  $.ajax({
    'dataType' : 'json',
    'type'     : 'post',
    'url'      : app.url('/Index/Index/getConfig'),
    'data'     : { token: app.store('token') }
  })
  .fail(function (res) {
    app.log('获取appid失败：', res);
    if (cb && cb.error) return cb.error(res);
  })
  .done(function (res) {
    if (res.code === 200) { 
      app.log('获取appid成功：', res);
      if (cb && cb.success) return cb.success(res.data.APPID);
    } else {
      app.log('获取appid失败：', res);
      if (cb && cb.error) return cb.error(res);
    }
  });
}

/**
 * 获取微信openid
 * @param  {Function} cb 回调函数
 */
app.getOpenid = function (cb) {
  var openid = app.store('openid');
  if (openid) {
    app.log('获取本地存储openid成功：', openid);
    if (cb && cb.success) return cb.success(openid);
  }
  app.getAppid({
    error: function (res) {
      app.log('获取openid失败：', res);
      if (cb && cb.error) return cb.error(res);
    },
    success: function (appid) {
      app._getOpenid(appid, cb, false);
    }
  });
}

/**
 * 获取微信用户信息
 * @param  {Function} cb 回调函数
 */
app.userInfo = function (cb) {
  var userinfo = app.store('userinfo');
  if (userinfo) {
    app.log('获取本地存储用户信息成功：', userinfo);
    if (cb && cb.success) return cb.success(userinfo);
  }
  app.getAppid({
    error: function (res) {
      app.log('获取用户信息失败：', res);
      if (cb && cb.error) return cb.error(res);
    },
    success: function (appid) {
      app._userInfo(appid, cb, false);
    }
  });
}

/**
 * 重新获取微信用户信息
 * @param  {[type]}   appid   appid
 * @param  {Function} cb      回调函数
 * @param  {Boolean}  isRetry 是否重新获取
 */
app._userInfo = function (appid, cb, isRetry) {
  var wxCode = app.getWxCode(appid, isRetry);
  if (wxCode) {
    $.ajax({
      'dataType' : 'json',
      'type'     : 'post',
      'url'      : app.url('/Index/Index/getUserInfo'),
      'data'     : { token: app.store('token'), data: { code: wxCode }}
    })
    .fail(function (res) {
      app.log('获取用户信息失败：', res);
      if (cb && cb.error) return cb.error(res);
    })
    .done(function (res) {
      if (res.code === 200) {
        app.log('获取用户信息成功：', res);
        app.store('userinfo', res.data.userinfo);
        if (cb && cb.success) return cb.success(res.data.userinfo);
      } else if (res.code === 100) {
        app._userInfo(appid, cb, true);
      } else {
        app.log('获取用户信息失败：', res);
        if (cb && cb.error) return cb.error(res);
      }
    });
  } 
}

/**
 * 重新获取openid
 * @param  {[type]}   appid   appid
 * @param  {Function} cb      回调函数
 * @param  {Boolean}  isRetry 是否重新获取
 */
app._getOpenid = function (appid, cb, isRetry) {
  var wxCode = app.getWxCode(appid, isRetry);
  if (wxCode) {
    $.ajax({
      'dataType' : 'json',
      'type'     : 'post',
      'url'      : app.url('/Index/Index/getOpenId'),
      'data'     : { token: app.store('token'), data: { code: wxCode }}
    })
    .fail(function (res) {
      app.log('获取openid失败：', res);
      if (cb && cb.error) return cb.error(res);
    })
    .done(function (res) {
      if (res.code === 200) {
        app.log('获取openid成功：', res);
        app.store('openid', res.data.openid);
        if (cb && cb.success) return cb.success(res.data.openid);
      } else if (res.code === 100) {
        app._getOpenid(appid, cb, true);
      } else {
        app.log('获取openid失败：', res);
        if (cb && cb.error) return cb.error(res);
      }
    });
  }
}

/**
 * 微信支付
 * @param  {Object} orderId 订单id
 * @param  {Object} orderNo 订单号
 */
app.wxPay = function (orderId, orderNo, balanced) {
  app.getAppid({
    error: function (res) {
      app.log('支付失败：', res);
    },
    success: function (appid) {
      app._wxPay(orderId, orderNo, appid, false, balanced);
    }
  });
}

/**
 * 重新微信支付
 * @param  {Object}  orderId  订单id
 * @param  {Object}  orderNo  订单号
 * @param  {Object}  appid    appid
 * @param  {Boolean} isRetry  是否重新获取
 * @param  {Object}  balanced 是否优先考虑余额支付
 */
app._wxPay = function (orderId, orderNo, appid, isRetry, balanced) {
  var wxCode = app.getWxCode(appid, isRetry);
  if (wxCode) {
    $.ajax({
      'dataType' : 'json',
      'type'     : 'post',
      'url'      : app.url('/Pay/Index/index'),
      'data'     : { token: app.store('token'), code: wxCode, order_id: orderId, balanced: balanced }
    })
    .fail(function (res) {
      app.log('支付失败：', res);
    })
    .done(function (res) {
      if (res.code === 200) {
        if (res.data && true === res.data.isOrderFinish) {
          var param = { 'id': orderId, 'order_no': orderNo, 'payway': 'wxpay' };
          return app.open('checkout.success.html', param);
        }

        if (typeof WeixinJSBridge == "undefined"){
          if( document.addEventListener ){
            document.addEventListener('WeixinJSBridgeReady', app.jsApiCall(res.data, orderId, orderNo), false);
          } else if (document.attachEvent){
            document.attachEvent('WeixinJSBridgeReady', app.jsApiCall(res.data, orderId, orderNo)); 
            document.attachEvent('onWeixinJSBridgeReady', app.jsApiCall(res.data, orderId, orderNo));
          }
        }else{
          app.jsApiCall(res.data, orderId, orderNo);
        }
      } else if (res.code === 100) {
        app._wxPay(orderId, orderNo, appid, true, balanced);
      } else {
        app.toast(res.msg);
      }
    });
  }
}

/**
 * 调起微信支付
 * @param  {Object} data    支付参数
 * @param  {Object} orderId 订单id
 * @param  {Object} orderNo 订单号
 */
app.jsApiCall = function (data, orderId, orderNo) {
  WeixinJSBridge.invoke( 'getBrandWCPayRequest', data,
    function(res){
      if(res.err_msg == "get_brand_wcpay_request:ok" ) {
        var param = { 'id': orderId, 'order_no': orderNo, 'payway': 'wxpay' };
        app.open('checkout.success.html', param);
      } else {
        app.log('支付失败：', res);
      }
    }
  );
}

/**
 * 用户登录验证
 * @param  {Function} cb 回调函数
 */
app.auth = function (cb) {
  var token = app.store('token');
  if (token) {
    app.log('登录成功token：', token);
    if (cb && cb.success) return cb.success();
  } else {
    app.getOpenid({
      error: function (res) {
        app.log('登录失败：', res);
        if (cb && cb.error) return cb.error(res);
      },
      success: function (openid) {
        $.ajax({
          'dataType' : 'json',
          'type'     : 'post',
          'url'      : app.url('/Sign/Index/login'),
          'data'     : { token: app.store('token'), data: { open_id: openid, source_type: 'weixin' }}
        })
        .fail(function (res) {
          app.log('登录失败：', res);
          if (cb && cb.error) return cb.error(res);
        })
        .done(function (res) {
          if (res.code === 200) {
            app.log('登录成功token：', res.data.uuid);
            app.store('token', res.data.uuid);
            app.store('member', res.data);
            if (cb && cb.success) return cb.success();
          } else {
            app.log('登录失败：', res);
            if (cb && cb.error) return cb.error(res);
          }
        });
      }
    });
  }
}

/**
 * 获取请求参数
 * @param  {Object} name 键名
 * @return {Object}      
 */
app.getQueryString = function (name){
  if (!name) return '';
  var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r!=null) return unescape(r[2]); return '';
}

/**
 * 获取请求参数并转成json
 * @param  {Object} url 请求地址
 * @return {Object} 
 */
app.parseQueryString = function (url) {
  return $.deparam.querystring(url || top.window.document.URL);
}

/**
 * 添加缓存数据
 * @param {Object} key
 * @param {Object} value
 */
app.store = function (key, value) {
	if (!key && !value) {
		return undefined;
	} else if (key && value) {
		var v = 'string' == typeof(value) ? value : JSON.stringify(value);
		localStorage.setItem(key, v);
	} else if (!value) {
		var v = localStorage.getItem(key);
		if (v && ('{' == v.charAt(0) || '[' == v.charAt(0))) {
			try { v = JSON.parse(v) } catch (e) {}	
		}
		return v;
	}
}

/**
 * 显示3.5秒的toast错误提示信息
 * @param {String} 提示字符串
 */
app.error = function (text) {
  mui.toast(text);
};

/**
 * 显示toast提示信息，如果需要微信APP直接改此
 * @param {Object} text
 */
app.toast = function (text) {
  mui.toast(text);
}

/**
 * 取得ArtTemplate并填充数据再把数据放于直接dom下。已做try catch处理
 * @param {Object} 用于放置构造出来的tpl代码的容器，可是jquery对象也可以是jquery的选择表达式
 * @return {String} 模板ID
 * @return {Object} 数据
 */
app.tpl = function (dom, tpl, data) {
	if (undefined !== data) {
		try { $(dom).html(template(tpl, data)); } catch (e) { app.log(e); };	
	} else if (undefined !== tpl) {
		return template(dom, tpl);
	}
};

/**
 * 补全URL地址
 * @param {String} API的URL后半段
 */
app.url = function (link) {
  link = link.replace(/^App\//,'/');
	console.log('请求链接：' + app.link.server + link);
	return app.link.server + link;
}

/**
 * 上传URL地址
 * @param {String} API的URL后半段
 */
app.uploadUrl = function (link) {
  console.log('上传链接：' + app.link.upload + link);
  return app.link.upload + link;
}

/**
 * 开发时用于打印日志，上线后此方法内不做任何事
 * @param {Object} data
 */
app.log = function (key, value) {
	if (undefined == value) {value = key, key = ''}
	
	if ('string' == typeof(value)) {
		console.log(key + value);
	} else {
		console.log(key + JSON.stringify(value));
	}
}

/**
 * 打开一个完全自己定义的新页面
 * @param {Object} link
 * @param {Object} data
 */
app.open = function (link, data) {
  if (link.lastIndexOf('/') === -1) {
    link = app.link.weixin + '/html/' + link;
  }
  if (data) {
    link += link.lastIndexOf('?') === -1 ? '?' : '';
    var oridata = app.parseQueryString(link);   
    link = link.substring(0, link.lastIndexOf('?') + 1); 
    link += $.param($.extend({}, oridata, data));
  } 

  var protocal = window.location.protocol;
  if (protocal !== 'https:' && protocal !== 'http:') {
    link = app.link.weixin + link;
  }

  if (link.indexOf('open.weixin.qq.com') === -1) {
    app.pages.push(link);
    app.putHis(link);
  }
  app.log('跳转链接：', link);

  return mui.openWindow({
      'url'       : link
  });
};

/**
 * 上传图片
 * @param  {Function} cb 回调函数
 */
app.wxUploadImage = function (cb) {
  var ary = [], len = 0;
  wx.chooseImage({
    count: 9, 
    sizeType: ['original', 'compressed'], 
    sourceType: ['album', 'camera'], 
    success: function (res) {
      len = res.localIds.length;
      for (var i = 0; res.localIds[i]; i++) {
        wx.uploadImage({
          localId: res.localIds[i], 
          isShowProgressTips: 1, 
          success: function (res) {
            ary.push(res.serverId);
            if (ary.length == len) { cb && cb(ary); };
          }
        });
      }
    }
  });
}

/**
 * 分享
 * @param  {Object} data 参数
 */
app.wxShare = function (data) {
  app.wxInit({
    error: function (res) {
      app.log('分享失败：', res);
    },
    success: function () {
      app.wxShareDom();
      app.wxShareEvent(data);
    }
  });
}

/**
 * 初始化DOM节点
 */
app.wxShareDom = function () {
  if (!$('.share-mask').length) {
    var container = $('<div/>').css({ 
      'position': 'fixed',
      'top': '0',
      'left': '0',
      'width': '100%',
      'height': '100%',
      'background': '#000',
      'opacity': '0.6',
      'z-index': '99999',
    }).addClass('share-mask').appendTo($('body', top.window.document)); 

    $('<img/>').css({ 
      'position': 'fixed',
      'top': '0',
      'left': '10%',
      'width': '80%',
      'z-index': '100000',
    })
    .attr('src', '../image/share.png').appendTo(container);

    $('.share-mask').on('tap', function () {
      $(this).toggle();
    });
  } else {
    $('.share-mask').show();
  }
}

/**
 * 分享绑定事件
 * @param  {Object} data 参数
 */
app.wxShareEvent = function (data) {
  // QQ
  wx.onMenuShareQQ({
    title: data.title, 
    desc: data.desc,
    link: data.link,
    imgUrl: data.imgUrl,
    success: function () {
      $('.share-mask').hide();
      if (data.success) return data.success;
    },
    cancel: function () {
      $('.share-mask').hide();
      if (data.cancel) return data.cancel;
    }
  });

  // QQ空间
  wx.onMenuShareQZone({
    title: data.title,
    desc: data.desc,
    link: data.link,
    imgUrl: data.imgUrl,
    success: function () {
      $('.share-mask').hide();
      if (data.success) return data.success;
    },
    cancel: function () {
      $('.share-mask').hide();
      if (data.cancel) return data.cancel;
    }
  });

  // 腾讯微博
  wx.onMenuShareWeibo({
    title: data.title,
    desc: data.desc,
    link: data.link,
    imgUrl: data.imgUrl,
    success: function () {
      $('.share-mask').hide();
      if (data.success) return data.success;
    },
    cancel: function () {
      $('.share-mask').hide();
      if (data.cancel) return data.cancel;
    }
  });

  // 微信朋友圈
  wx.onMenuShareTimeline({
    title: data.title, 
    link: data.link, 
    imgUrl: data.imgUrl, 
    success: function () {
      $('.share-mask').hide();
      if (data.success) return data.success;
    },
    cancel: function () {
      $('.share-mask').hide();
      if (data.cancel) return data.cancel;
    }
  });

  // 微信好友
  wx.onMenuShareAppMessage({
    title: data.title, 
    desc: data.desc, 
    link: data.link, 
    imgUrl: data.imgUrl, 
    type: data.type, 
    dataUrl: data.dataUrl, 
    success: function () {
      $('.share-mask').hide();
      if (data.success) return data.success;
    },
    cancel: function () {
      $('.share-mask').hide();
      if (data.cancel) return data.cancel;
    }
  });
}

/**
 * 添加浏览记录
 * @param {Object} value
 */
app.putHis = function (value) {
  var his = app.store('history');
  if (his) {    
    if (his[his.length - 1] === value) return;
    his.push(value);
  } else {
    his = [value];
  }
  app.store('history', his);
}

/**
 * 清空浏览记录
 */
app.clearHis = function () {
  app.store('history', []);
}

/**
 * 获取上一条浏览记录
 * @return {Object} value
 */
app.getHis = function () {
  var his = app.store('history');
  if (!his || !his.length) return;
  return his[his.length - 2] || his[his.length - 1];
}

/**
 * 获取上一条浏览记录并删除
 * @return {Object} value
 */
app.popHis = function () {
  var his = app.store('history');
  if (!his || !his.length) return;
  if (his.length === 1) return app.link.weixin;
  his.pop();
  var value = his.pop();
  app.store('history', his);
  return value;
}

if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(predicate) {
      if (this == null) {
        throw new TypeError('Array.prototype.find called on null or undefined');
      }
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }
      var list = Object(this);
      var length = list.length >>> 0;
      var thisArg = arguments[1];
      var value;

      for (var i = 0; i < length; i++) {
        if (i in list) {
          value = list[i];
          if (predicate.call(thisArg, value, i, list)) {
            return value;
          }
        }
      }
      return undefined;
    }
  });
}

app.tryResetPullLoading = function () {
	try {
	if ($('.container-pull-refresh').length == 0) { return; }
	
	var pullrefresh = mui('.container-pull-refresh').pullRefresh();
	pullrefresh.endPullupToRefresh();
	pullrefresh.endPulldownToRefresh();
	} catch (e) {}
}

app.image = app.avatar = function (v) {
  if (v && (!v.indexOf('https:') || !v.indexOf('http:'))) {
    return v;
  }
  if (v && v.charAt(0) !== '/') {
    v = '/' + v;
  }
  return v ? (app.link.image + v) : '../image/icon-no-image.png';
};

app.thumb = function (url) {
  if (url && (!url.indexOf('https:') || !url.indexOf('http:'))) {
    return url;
  }
  if (!url) { return '../image/icon-no-image.png'; }

  if (url && url.charAt(0) !== '/') {
    url = '/' + url;
  }
  var idx = url.lastIndexOf('.');
  var zip = url.substr(0, idx) + '_100_100' + url.substr(idx);
  
  return app.link.image + zip;
}

template.helper('avatar', function (v) {
  if (v && v.charAt(0) !== '/') {
    v = '/' + v;
  }
	return v ? (app.link.image + v) : '../image/icon-no-image.png';
});

template.helper('image', function (v) {
  if (v && v.charAt(0) !== '/') {
    v = '/' + v;
  }
	return v ? (app.link.image + v) : '../image/icon-no-image.png';
});

template.helper('thumb', function (url) {
  if (url && url.charAt(0) !== '/') {
    url = '/' + url;
  }
	var idx = url.lastIndexOf('.');
	var zip = url.substr(0, idx) + '_100_100' + url.substr(idx);
	return url ? (app.link.image + zip) : '../image/icon-no-image.png';
});

template.helper('price', function (v) {
	return v ? (v/100) : '0.00';
});
